package com.tanhua.dubbo.api.service;

import com.aliyunsms.template.SmsTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.exception.BusinessException;
import com.tanhua.dubbo.api.interceptor.UserHolder;
import com.tanhua.model.domain.User;
import com.tanhua.dubbo.api.utils.JwtUtil;
import com.tanhua.model.vo.ExceptionResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private UserApi userApi;

    public void sendSms(String phone) throws Exception{



        //1 产生随机验证码
//        String code = RandomUtils.getRandomCode();
        String code = "123456";
        //2 发送验证码
//        smsTemplate.sendSms(phone,code);
        //3 将验证码存入redis，key：login_code_xxxx    存活时间5分钟
        redisTemplate.opsForValue().set("login_code_"+phone,code, Duration.ofMinutes(5));

    }

    public Map loginVerification(String phone, String verificationCode) {
        //1  从redis中取出验证码
        String redisCode = redisTemplate.opsForValue().get("login_code_" + phone);
        //2 校验验证码，首先不能为空，其次比较是否一致
        if (!(StringUtils.isNotBlank(redisCode)&&StringUtils.isNotBlank(verificationCode)&&redisCode.equals(verificationCode))){
//            throw new RuntimeException("校验码验证失败");
            throw new BusinessException(ExceptionResult.verificationCodeError());
        }

//        if (StringUtils.isNotBlank(redisCode)&&StringUtils.isNotBlank(verificationCode)&&redisCode.equals(verificationCode)){
//
//        }else{
//            throw new RuntimeException("校验码验证失败");
//        }
        //3 根据手机号码去数据可查找，
        Boolean isNew = false;
        User user = userApi.findByMobile(phone);
        //3.1 如果没有找到，是新用户，新用户先保存到数据库中,然后再生成token
        if (user==null){
            //新增
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
        }

        // 3.2 如果找到了，是老用户，直接生成token  //4 生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",user.getId());
        map.put("mobile",phone);
        String token = JwtUtil.createToken(map);
        //5 组装返回结果，返回
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("isNew",isNew);
        return resultMap;
    }
}
